﻿using CMS.DataAccess;
using CMS.Utils;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Net;

namespace CMS.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class MyController: ControllerBase
    {
        protected HttpContext httpContext;
        protected DbInstance dbInstance;
        public MyController() : base() 
        {
            httpContext = ServiceLoader.GetService<IHttpContextAccessor>().HttpContext!;
            dbInstance = ServiceLoader.GetService<DbInstance>();
            httpContext.Response.OnStarting(Func, httpContext);
        }
        protected Task Func(object obj)
        {
            var context = obj as HttpContext;
            if (context?.Response.StatusCode == (int)HttpStatusCode.OK)
            {
                Commit();
            }
            else
            {
                Abort();
            }
            return Task.CompletedTask;
        }
        protected void Commit()
        {
            this.dbInstance.Commit();
        }
        protected void Abort()
        {
            this.dbInstance.Rollback();
        }
    }
}
